package com.txhy.certificatechain.ui.activity.user;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.google.gson.Gson;
import com.ninetripods.aopermission.permissionlib.annotation.NeedPermission;
import com.txhy.certificatechain.R;
import com.txhy.certificatechain.model.bean.PersonCardBean;
import com.txhy.certificatechain.presenter.user.UpLoadPresenter;
import com.txhy.certificatechain.ui.activity.base.BaseActivity;
import com.txhy.certificatechain.ui.utils.DiaLogUtils;
import com.txhy.certificatechain.ui.view.user.UpLoadView;
import com.txhy.certificatechain.ui.widget.CropView;
import com.txhy.certificatechain.utils.BitmapUtil;
import com.txhy.certificatechain.utils.FileUtil;
import com.txhy.certificatechain.utils.ToastUtil;
import com.txhy.certificatechain.utils.UIUtils;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/*
 * -----------------------------------------------------------------
 * Copyright (C) 2018-2030, by your company, All rights reserved.
 * -----------------------------------------------------------------
 * 文    件: UploadCardIDActivity.java
 * 作    者: 侯建军
 * 版    权: 1.0.0
 * 描    述: 上传身份认识信息
 * 创建时间: 2018/9/20 17:38
 * 更新时间：2018/9/20 17:38
 * -----------------------------------------------------------------
 * 2018/9/20 17:38: 创建 UploadCardIDActivity.java (侯建军);
 * -----------------------------------------------------------------
 */
public class UploadCardIDActivity extends BaseActivity<UpLoadView, UpLoadPresenter> implements UpLoadView {
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.img_zheng)
    CropView img_zheng;

    @BindView(R.id.img_fan)
    CropView img_fan;
    @BindView(R.id.tv_next)
    TextView tv_next;
    @BindView(R.id.linear_zheng)
    LinearLayout linear_zheng;
    @BindView(R.id.linear_fan)
    LinearLayout linear_fan;

    @BindView(R.id.img_yanZheng)
    ImageView img_yanZheng;
    @BindView(R.id.img_yanFan)
    ImageView img_yanFan;

    @BindView(R.id.im_left)
    ImageView im_left;

    private boolean zheng, fan;
    private String userId;
    private String zhengFile, fanFile;
    private PersonCardBean personCardBean = new PersonCardBean();

    @Override
    protected UpLoadPresenter createPresenter() {
        return new UpLoadPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_upload_card_id;
    }

    @Override
    public void initView() {
        super.initView();
        tv_title.setText(UIUtils.getString(R.string.zengjia));
        im_left.setVisibility(View.VISIBLE);
        DiaLogUtils.showCardDialog(UploadCardIDActivity.this);
        userId=getIntent().getStringExtra("userId");
    }

    @OnClick({R.id.frame_cardZheng, R.id.frame_cardFan, R.id.tv_next, R.id.im_left})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.im_left:
                finish();
                break;
            case R.id.frame_cardZheng:
                openCamera(CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                break;
            case R.id.frame_cardFan:
                openCamera(CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
                break;
            case R.id.tv_next:
                if (zheng && fan) {
                    mPresenter.SendCard(new Gson().toJson(personCardBean));
                } else {
                    ToastUtil.showShort(UploadCardIDActivity.this, UIUtils.getString(R.string.qingwancheng));
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //在相册里面选择好相片之后调回到现在的这个activity中
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
                String filePath = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
                if (!TextUtils.isEmpty(contentType)) {
                    if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
                    } else if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
                    } else if (CameraActivity.CONTENT_TYPE_BANK_CARD.equals(contentType)) {

                    }
                }
            }
        }
    }


    @SuppressLint("MissingPermission")
    @NeedPermission(value = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode = 0)
    private void openCamera(String type) {
        Intent intent = new Intent(UploadCardIDActivity.this, CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtil.getSaveFile(getApplication()).getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, type);
        startActivityForResult(intent, 1);
    }

    /**
     * 解析身份证图片
     *
     * @param idCardSide 身份证正反面
     * @param filePath   图片路径
     */
    private void recIDCard(final String idCardSide, final String filePath) {
        try{
            IDCardParams param = new IDCardParams();
            param.setImageFile(new File(filePath));
            // 设置身份证正反面
            param.setIdCardSide(idCardSide);
            // 设置方向检测
            param.setDetectDirection(true);
            // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
            param.setImageQuality(40);

            OCR.getInstance(this).recognizeIDCard(param, new OnResultListener<IDCardResult>() {
                @Override
                public void onResult(IDCardResult result) {
                    if (result != null) {
                        if (idCardSide.equals(IDCardParams.ID_CARD_SIDE_FRONT)) {
                            zhengFile = filePath;
                            personCardBean.setId(userId);
                            personCardBean.setBirthday(result.getBirthday()+"");
                            personCardBean.setCardName(result.getName()+"");
                            personCardBean.setCardAddress(result.getAddress()+"");
                            personCardBean.setCardNo(result.getIdNumber()+"");
                            personCardBean.setSex(result.getGender()+"");
                            personCardBean.setRace(result.getEthnic()+"");
                            if(!TextUtils.isEmpty(result.getIdNumber()+"")){
                                mPresenter.upLoadImg(BitmapUtil.compressImage(filePath), "1");
                            }else{
                                ToastUtil.showLong(UploadCardIDActivity.this, UIUtils.getString(R.string.qingjiangshen));
                            }

                        } else if (idCardSide.equals(IDCardParams.ID_CARD_SIDE_BACK)) {
                            fanFile = filePath;
                            personCardBean.setCardTerm(result.getSignDate() + "-" + result.getExpiryDate());
                            personCardBean.setBelongTo(result.getIssueAuthority()+"");
                            mPresenter.upLoadImg(BitmapUtil.compressImage(filePath), "2");
                        }

                    }
                }

                /**
                 *
                 * @param error
                 */
                @Override
                public void onError(OCRError error) {
                    ToastUtil.showLong(UploadCardIDActivity.this, UIUtils.getString(R.string.qingjiangshen));
                }
            });

        }catch (Exception e){
            //进行OCR认证
            OCR.getInstance(this).initAccessTokenWithAkSk(
                    new OnResultListener<AccessToken>() {
                        @Override
                        public void onResult(AccessToken result) {
                            // 本地自动识别需要初始化
//                        initLicense();
                            Log.d("MainActivity", "onResult: " + result.toString());
                        }

                        @Override
                        public void onError(OCRError error) {
                            error.printStackTrace();
                            Log.e("MainActivity", "onError: " + error.getMessage());
                        }
                    }, getApplicationContext(),
                    // 需要自己配置 https://console.bce.baidu.com
                    "MUwLqftifFp66e3xV313Mosk",
                    // 需要自己配置 https://console.bce.baidu.com
                    "s5Kf2Osv5bA0peho1IFOj7GQcvDOy7Tu");

            OCR.getInstance(this).initAccessToken(new OnResultListener<AccessToken>() {
                @Override
                public void onResult(AccessToken result) {
                    // 调用成功，返回AccessToken对象
                    String token = result.getAccessToken();
                }
                @Override
                public void onError(OCRError error) {
                    // 调用失败，返回OCRError子类SDKError对象
                }
            }, getApplicationContext());

            ToastUtil.showLong(UploadCardIDActivity.this, UIUtils.getString(R.string.qingjiangshen));
        }
    }

    @Override
    public void showProgress(String tipString) {
        showWaitingDialog(tipString);
    }

    @Override
    public void hideProgress() {
        hideWaitingDialog();
    }

    @Override
    public void upLoadSuccess(String msg, String filePath) {
        switch (msg) {
            case "1"://正
                img_zheng.setFilePath(zhengFile);
                img_zheng.setBackgroundResource(0);
                linear_zheng.setVisibility(View.GONE);
                img_yanZheng.setVisibility(View.VISIBLE);
                zheng = true;
                personCardBean.setCardFaceUrl(filePath);
                break;
            case "2"://反
                img_fan.setFilePath(fanFile);
                img_fan.setBackgroundResource(0);
                linear_fan.setVisibility(View.GONE);
                img_yanFan.setVisibility(View.VISIBLE);
                fan = true;
                personCardBean.setCardConUrl(filePath);
                break;
        }
    }

    @Override
    public void upLoadFail(String msg) {
        ToastUtil.showShort(UploadCardIDActivity.this, msg);
    }

    @Override
    public void upMsgSuccess(String msg) {
//        Intent intent=new Intent(UploadCardIDActivity.this, FaceLivenessExpActivity.class);
//        intent.putExtra("id",userId);
//        startActivity(intent);
    }
    @Override
    public void upMsgFail(String msg) {
        ToastUtil.showShort(UploadCardIDActivity.this, msg);
    }
}